import Vue from 'vue'
import VueRouter from 'vue-router'
// import HomeView from '../views/HomeView.vue'
import login from '../page/login/LoginIndex.vue'
import HomeView from '../page/Main/MainIndex.vue' // 这种引入方式的缺点：首屏加载慢，因为要运行所有的组件
// import Main from '../page/Main/MainIndex.vue'
import store from '@/store/index'

Vue.use(VueRouter)
/* 
  引入方式：
    1.import 这种引入方式的缺点：首屏加载慢，因为要运行所有的组件
    2.路由懒加载   优点：首屏加载时不运行，只有在进入这个路由的时候才会加载组件
*/

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const routes = [{
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/category/:id',
    name: 'category',
    meta: {
      title: ''
    },
    component: () => import('@/page/Main/Category')
  },
  {
    path: '/shopdetail/:id',
    name: 'ShopDetail',
    component: () => import('@/page/Main/ShopDetail')
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/cart',
    name: ' cart',
    component: () => import('@/page/Cart'),

  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.

    // 路由懒加载   优点：首屏加载时不运行，只有在进入这个路由的时候才会加载组件
    component: () => import( /* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  next();
  if(store.state.userInfor.userName=='' && to.path=='/cart'){
    alert('请登录')
    next('/login')
  }
})

export default router